package jin.courses.jan21;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
	//dao里只做数据库操作
	Connection con=null;
	
	PreparedStatement ps=null;
	
	BaseDao baseDao=new BaseDao();
	
	ResultSet rs=null;
	public User getUserbyName(String name) throws SQLException{
		con=baseDao.getCon();
		String sql="select * from user where username=?";
		ps=con.prepareStatement(sql);
		ps.setString(1, name);
		rs=ps.executeQuery();
		String pwd="";
		int id=0;
		while(rs.next()){
			pwd=rs.getString("pwd");
			id=rs.getInt("id");
		}
		User u=new User(name,pwd,id);
		closeData();
		return u;
	}
	public boolean addUser(User u) throws SQLException{
		boolean flag=false;
		String sql="insert into user (username,pwd) values (?,?)";
		con=baseDao.getCon();
		ps=con.prepareStatement(sql);
		ps.setString(1, u.getName());
		ps.setString(2, u.getPwd());
		int a=ps.executeUpdate();
		if(a>0){
			flag=true;
		}
		closeData();
		return flag;
		
	}
	
	
	public void closeData() throws SQLException{
		if(rs!=null){
			rs.close();
		}
		if(ps!=null){
			ps.close();
		}
		if(con!=null){
			con.close();
		}
	}	

}
